using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;

namespace WIT.DAQ.Core.Helper;

/// <summary>
/// 时间帮助类
/// </summary>
internal class TimeHelper
{
	internal static readonly List<string> URIS = new List<string> { "http://www.gov.cn/", "http://www.jiangsu.gov.cn/", "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=1", "https://www.baidu.com/", "https://www.usa.gov/" };

	/// <summary>
	/// 将本地时间转换为时间戳，效果等同于javascript的getTime()。
	/// [时间戳：从UTC时间的1970年1月1日0时0分0秒到现在的毫秒数]
	/// </summary>
	/// <param name="datetime"></param>
	/// <returns></returns>
	internal static long ConvertToTimestamp(DateTime datetime)
	{
		return Convert.ToInt64((datetime.ToUniversalTime() - Convert.ToDateTime("1970-01-01 00:00:00")).TotalMilliseconds);
	}

	/// <summary>
	/// 将时间戳转换为本地时间
	/// [时间戳：从UTC时间的1970年1月1日0时0分0秒到现在的毫秒数]
	/// </summary>
	/// <param name="timestamp"></param>
	/// <returns></returns>
	internal static DateTime ConvertToDateTime(long timestamp)
	{
		return Convert.ToDateTime("1970-01-01 00:00:00").AddMilliseconds(timestamp).ToLocalTime();
	}

	internal static bool GetBeijingTime(out DateTime dateTime, string uri = "http://www.gov.cn/")
	{
		bool flag = false;
		dateTime = default(DateTime);
		try
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
			httpWebRequest.Method = "HEAD";
			httpWebRequest.AllowAutoRedirect = false;
			HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			string responseHeader = httpWebResponse.GetResponseHeader("Date");
			httpWebResponse.Close();
			CultureInfo provider = new CultureInfo("en-US");
			flag = DateTime.TryParseExact(responseHeader, "r", provider, DateTimeStyles.None, out var result);
			dateTime = result.AddHours(8.0);
		}
		catch
		{
			flag = false;
		}
		return flag;
	}
}
